package com.bdmc.smokesensor.controller;

import java.util.Map;

import com.bdmc.smokesensor.Utils.Msg;
import com.bdmc.smokesensor.Utils.ResultUtil;
import com.bdmc.smokesensor.entity.Smk_GroupCompany;
import com.bdmc.smokesensor.entity.Sys_Log;
import com.bdmc.smokesensor.iservices.ISmk_BuildingsService;
import com.bdmc.smokesensor.iservices.ISmk_GroupCompanyService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/gcp",method = RequestMethod.POST)
public class Smk_GroupCompanyController extends BaseController{

    @Autowired
    private ISmk_GroupCompanyService _gcpSvs;

    @Autowired
    private ISmk_BuildingsService _buildSvs;

    @RequestMapping(value = "/list" )
    public Msg list(@RequestBody Map<String, Object> reqMap) {
        int page = Integer.parseInt(reqMap.get("page").toString());
        int rows = Integer.parseInt(reqMap.get("rows").toString());
        String groupName=reqMap.get("groupName").toString();
        int dep_id=Integer.valueOf(request.getAttribute("dep_id").toString());
        return ResultUtil.success(_gcpSvs.findByPageable(dep_id,","+dep_id+",",groupName,page, rows));
    }

    /**
     * 数据新增或更新，save方法可以执行添加也可以执行更新，如果需要执行持久化的实体存在主键值则更新数据，如果不存在则添加数据。
     */

    @RequestMapping(value = "/save")
    public Msg save(@RequestBody Smk_GroupCompany gc) {
        String action = gc.getId()>0?"修改:":"新增:";
        Smk_GroupCompany g = _gcpSvs.save(gc);
        if(g!=null&&g.getId()>0){
            Sys_Log log = new Sys_Log(getLoginName(), getLocalIp() , "联网单位", action+g.getGroupName());
            _logSvs.save(log);
            return ResultUtil.success();
        }else
        {
            return ResultUtil.error(-1,"操作失败，请联系管理员。");
        }
    }

      /**
     * 删除设备信息，删除信息后返回剩余信息
     */
    @RequestMapping(value = "/delete")
    public Msg delete(@RequestBody Map<String,Integer> map) {
        int id =Integer.valueOf(map.get("id"));
        _gcpSvs.deleteById(id);
        Long count = _buildSvs.countBySmkGroupCompanyId(id);
        if(count>0){
            return ResultUtil.error(-1,"联网单位存在子单位，无法删除。");            
        }
        Sys_Log log = new Sys_Log(getLoginName(), getLocalIp() , "联网单位", "删除："+id);
        _logSvs.save(log);
        return ResultUtil.success();
    }

}